package com.mk.listener;

import cn.hutool.json.JSONUtil;
import com.mk.common.request.MonitorWaterReq;
import com.mk.event.MqttMessageEvent;
import com.mk.service.WaterMonitorService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * @author XueJinCha
 */
@Component
@RequiredArgsConstructor
public class MqttMessageListener {

    private final WaterMonitorService waterMonitorService;

    /**
     * （接收消息:步骤五）事件监听器中处理消息 说明：此方法将接收到上方 MqttUtil.publishReceivedMessage() 发布的事件并处理这些消息
     *
     * @param event 接收到的事件
     */
    @EventListener
    public void handleMqttMessage(MqttMessageEvent event) {
        String topic = event.getTopic();
        String payload = event.getPayload();
        System.out.println("处理接收到的消息: 主题 = " + topic + ", 内容 = " + payload);
        MonitorWaterReq req = JSONUtil.toBean(payload, MonitorWaterReq.class);
        waterMonitorService.waterMonitor(req);
    }
}

